package com.atguigu.chapter;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @ClassName: SocketWordCount
 * @Description:
 * @Author: kele
 * @Date: 2021/3/31 11:44
 **/
public class SocketWordCount {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment sexec = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> ds = sexec.socketTextStream("hadoop162", 8888);

        SingleOutputStreamOperator<Tuple2<String, Long>> ds1 = ds.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Long>> collector) throws Exception {

                String[] words = line.split(" ");

                for (String word : words) {

                    collector.collect(Tuple2.of(word, 1L));

                }
            }
        });

        KeyedStream<Tuple2<String, Long>, String> ds2 = ds1.keyBy((KeySelector<Tuple2<String, Long>, String>) words -> words.f0);

        SingleOutputStreamOperator<Tuple2<String, Long>> sum = ds2.sum(1);

        sum.print();

        sexec.execute();

    }

}
